package rp.lee.weblog;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iih5.netbox.NetBoxEngine;
import com.iih5.netbox.NetBoxEngineSetting;
import com.iih5.netbox.codec.ws.WsTextForDefaultJsonDecoder;
import com.iih5.netbox.codec.ws.WsTextForDefaultJsonEncoder;

/**
 * Hello world!
 *
 */
public class App {
	protected static final Logger logger = LoggerFactory.getLogger(App.class);
	public static void main(String[] args) throws Exception {
		System.out.println("~======user.dir=====" + System.getProperty("user.dir"));
		
		startTcpServer(8865);
		startHttpServer(8765);
	}
	
	public static void startTcpServer(int port) throws Exception {
		logger.info("Tcp服务端启动中....");
		NetBoxEngineSetting setting  = new NetBoxEngineSetting();
		setting.setBasePackage("rp.lee.weblog");//handler所在目录
		setting.setPort(port);
		setting.setProtocolCoder(new WsTextForDefaultJsonEncoder(),new WsTextForDefaultJsonDecoder());
		setting.setDebug(true);
		
		logger.info("扫描{}下的所有Handler.", setting.getBasePackage());
		NetBoxEngine boxEngine = new NetBoxEngine();
		boxEngine.setSettings(setting);
		boxEngine.start();//启动服务器
	}
	
	public static void startHttpServer(int port) throws Exception {
		logger.info("Http服务端启动中....");
		
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							// server端接收到的是httpRequest，所以要使用HttpRequestDecoder进行解码
							ch.pipeline().addLast(new HttpRequestDecoder());
							// server端发送的是httpResponse，所以要使用HttpResponseEncoder进行编码
							ch.pipeline().addLast(new HttpResponseEncoder());
							ch.pipeline().addLast(new HttpObjectAggregator(1048576));
							ch.pipeline().addLast(new HttpServerInboundHandler());
						}
					}).option(ChannelOption.SO_BACKLOG, 128)
					.childOption(ChannelOption.SO_KEEPALIVE, true);
			b.bind(port).sync();
//			ChannelFuture f = b.bind(port).sync();
//			f.channel().closeFuture().sync();
		} catch(Exception e) {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
		
		logger.info("Http服务端[port={}]启动Success....", port);
	}
}
